<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// ----- 数据状态 -----
const tasks = reactive<any[]>([])
const patrolDetails = reactive<any[]>([])
const patrols = reactive<any[]>([])
const photos = reactive<any[]>([])

// 筛选状态
const filterTaskName = ref('')
const filterType = ref('')
const filterArea = ref('')
const filterStatus = ref('')

const selectedTask = ref<any>(null)
const showDialog = ref(false)
const editingTask = ref<any>(null)

const typeOptions = ['夜巡', '日巡', '例行']
const areaOptions = ['A区', '出入口', '停车场']

// 过滤任务列表
const filteredTasks = computed(() => {
  return tasks.filter(t => {
    return (!filterTaskName.value || t.taskName.includes(filterTaskName.value))
        && (!filterType.value || t.patrolType === filterType.value)
        && (!filterArea.value || t.patrolArea === filterArea.value)
        && (!filterStatus.value || t.status === filterStatus.value)
  })
})

// 状态文本与颜色
function statusText(s: string) { return s === '0' ? '未开始' : s === '1' ? '进行中' : '已完成' }
function statusClass(s: string) { return s === '0' ? 'status-0' : s === '1' ? 'status-1' : 'status-2' }

// 通过ID查找巡逻详情
function detailById(id: number) {
  if (id === undefined || id === null) return {}
  return patrolDetails.find(d => d.id === id) || {}
}

// ---------------- API 调用 ----------------
async function fetchTasks() {
  try {
    const res = await fetch('http://localhost:9030/task/list')
    const data = await res.json()
    tasks.length = 0
    data.rows?.forEach((t: any) => tasks.push(t))
  } catch (e) {
    console.error(e)
    ElMessage.error('获取任务列表失败')
  }
}

async function fetchPatrolDetails() {
  try {
    const res = await fetch('http://localhost:9030/detail/list')
    const data = await res.json()
    patrolDetails.length = 0
    data.rows?.forEach((d: any) => patrolDetails.push(d))
  } catch (e) { console.error(e); ElMessage.error('获取巡逻详情失败') }
}

async function fetchPatrols() {
  try {
    const res = await fetch('http://localhost:9030/patroll/list')
    const data = await res.json()
    patrols.length = 0
    data.rows?.forEach((p: any) => patrols.push(p))
  } catch (e) { console.error('获取巡逻记录失败:', e); ElMessage.error('获取巡逻记录失败') }
}

async function fetchPhotos() {
  try {
    const res = await fetch('http://localhost:9030/photos/list')
    const data = await res.json()
    photos.length = 0
    if (data.rows && Array.isArray(data.rows)) {
      data.rows.forEach((p: any) => photos.push(p))
    }
  } catch (e) { console.error(e); ElMessage.error('获取照片失败') }
}

// ---------------- 任务操作 ----------------
function selectTask(t: any) { selectedTask.value = t }
function openCreate() { editingTask.value = { status: '0' }; showDialog.value = true }
function openEdit(t: any) { editingTask.value = { ...t }; showDialog.value = true }
function saveTask() { showDialog.value = false } // TODO: 调用后端 API 保存

// ---------------- 地图逻辑 ----------------
let globalMap: any = null

function initMap() {
  if (globalMap) return
  const mapContainer = document.getElementById('mapContainer')
  if (!mapContainer) return

  globalMap = new AMap.Map(mapContainer, {
    zoom: 17,
    center: [116.481488, 39.996141],
  })

  globalMap.addControl(new AMap.Scale())
  globalMap.addControl(new AMap.ToolBar())

  const marker = new AMap.Marker({
    position: [116.481488, 39.996141],
    title: '北京万科城市花园'
  })
  globalMap.add(marker)
}

function loadAMapScript() {
  if ((window as any).AMap) {
    initMap()
    return
  }

  ;(window as any)._AMapSecurityConfig = { securityJsCode: "3294aa3d3b2a482383e087452080b0d9" }

  const script = document.createElement('script')
  script.src = 'https://webapi.amap.com/maps?v=2.0&key=eec0d44028d6ba50a0506f86c9feeeea&plugin=AMap.Scale,AMap.ToolBar&callback=initAMap'
  script.onerror = () => console.error('高德地图API加载失败')
  document.head.appendChild(script)
}

;(window as any).initAMap = () => { initMap() }

// ---------------- 生命周期 ----------------
onMounted(() => {
  fetchTasks()
  fetchPatrolDetails()
  fetchPatrols()
  fetchPhotos()
  loadAMapScript()
})

// ---------------- 图片加载处理 ----------------
function handleImageError(photo: any, event: Event) {
  const img = event.target as HTMLImageElement
  console.warn('图片加载失败:', photo.patrol_photo)
  img.src = 'https://via.placeholder.com/150?text=加载失败'
}

function handleImageLoad(photo: any, event: Event) {
  console.log('图片加载成功:', photo.patrol_photo)
}
</script>

<template>
  <div class="app-wrap">
    <el-row justify="space-between" align="middle" class="mb-3">
      <el-col>
        <h2 style="margin:0 0 8px 0">安保巡逻管理控制台</h2>
      </el-col>
      <el-col>
        <el-button type="primary" @click="openCreate">新建任务</el-button>
      </el-col>
    </el-row>

    <el-row :gutter="16">
      <!-- 左侧任务列表 -->
      <el-col :span="6">
        <el-card>
          <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
            <div style="font-weight:600">任务列表</div>
            <div class="muted" style="font-size:12px">{{ filteredTasks.length }} 项</div>
          </div>

          <el-input v-model="filterTaskName" placeholder="按任务名搜索" clearable size="small" class="mb-2"/>
          <el-select v-model="filterType" placeholder="巡逻类型" clearable size="small" class="mb-2">
            <el-option v-for="t in typeOptions" :key="t" :label="t" :value="t"/>
          </el-select>
          <el-select v-model="filterArea" placeholder="区域" clearable size="small" class="mb-2">
            <el-option v-for="a in areaOptions" :key="a" :label="a" :value="a"/>
          </el-select>
          <el-select v-model="filterStatus" placeholder="状态" clearable size="small">
            <el-option label="未开始" value="0"/>
            <el-option label="进行中" value="1"/>
            <el-option label="已完成" value="2"/>
          </el-select>

          <el-scrollbar style="max-height:520px; margin-top:8px">
            <div v-for="task in filteredTasks" :key="task.id" class="task-item" @click="selectTask(task)">
              <div style="flex:1">
                <div style="font-weight:600">{{ task.taskName }}</div>
                <div class="muted" style="font-size:12px">{{ task.patrolType }} · {{ task.patrolArea }} · {{ task.patrolFrequency }}</div>
                <div class="muted" style="font-size:12px">{{ task.startTime }} - {{ task.endTime }}</div>
              </div>
              <div style="text-align:right;min-width:80px">
                <div :class="statusClass(task.status)" style="font-weight:600">{{ statusText(task.status) }}</div>
              </div>
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>

      <!-- 右侧主区 -->
      <el-col :span="18">
        <el-card class="mb-3 map-card">
          <div id="mapContainer"></div>
        </el-card>

        <el-row :gutter="12" class="mb-3">
          <el-col :span="12">
            <el-card>
              <div style="font-weight:600;margin-bottom:8px">巡逻记录</div>
              <el-table :data="patrols" height="240" border>
                <el-table-column prop="buserId" label="巡逻员ID" width="100"/>
                <el-table-column prop="buserPhone" label="手机" width="130"/>
                <el-table-column label="路线/明细" width="220">
                  <template #default="{row}">
                    <div>{{ detailById(row.patrolDetailId).patrolRoute || '-' }}</div>
                    <div class="muted" style="font-size:12px">{{ detailById(row.patrolDetailId).patrolArea || '' }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="patrolTime" label="打卡时间" width="180"/>
              </el-table>
            </el-card>
          </el-col>

          <el-col :span="12">
            <el-card>
              <div style="font-weight:600;margin-bottom:8px">打卡照片</div>
              <el-row :gutter="8">
                <el-col v-for="ph in photos" :key="ph.id" :span="8">
                  <div style="position:relative; overflow:hidden; border:1px solid #eee; border-radius:4px;">
                    <img
                        :src="ph.patrol_photo || 'https://via.placeholder.com/150?text=无图'"
                        class="photo"
                        :alt="'巡逻照片 ' + ph.id"
                        @error="(e) => handleImageError(ph, e)"
                        @load="(e) => handleImageLoad(ph, e)"
                    />
                  </div>
                  <div style="font-size:12px;margin-top:4px">
                    员 {{ ph.buser_id }} · <span class="muted">{{ ph.picture_time }}</span>
                  </div>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>

        <el-card>
          <div style="font-weight:600;margin-bottom:8px">任务详情</div>
          <div v-if="selectedTask">
            <el-row :gutter="12">
              <el-col :span="8"><div class="muted">任务名</div><div style="font-weight:600">{{ selectedTask.taskName }}</div></el-col>
              <el-col :span="8"><div class="muted">类型 / 区域</div><div style="font-weight:600">{{ selectedTask.patrolType }} · {{ selectedTask.patrolArea }}</div></el-col>
              <el-col :span="8"><div class="muted">频率</div><div style="font-weight:600">{{ selectedTask.patrolFrequency }}</div></el-col>

              <el-col :span="12" style="margin-top:12px"><div class="muted">路线</div><div style="font-weight:600">{{ selectedTask.patrolRoute }}</div></el-col>
              <el-col :span="12" style="margin-top:12px"><div class="muted">时间范围</div><div style="font-weight:600">{{ selectedTask.startTime }} — {{ selectedTask.endTime }}</div></el-col>
            </el-row>
          </div>
          <div v-else class="muted">请在左侧选择任务以查看详情</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新建/编辑任务弹窗 -->
    <el-dialog :title="editingTask?.id ? '编辑任务' : '新建任务'" v-model="showDialog" width="600px">
      <el-form :model="editingTask" label-width="90px">
        <el-form-item label="任务名称">
          <el-input v-model="editingTask.taskName"/>
        </el-form-item>
        <el-form-item label="巡逻类型">
          <el-select v-model="editingTask.patrolType" placeholder="请选择">
            <el-option v-for="t in typeOptions" :key="t" :label="t" :value="t"/>
          </el-select>
        </el-form-item>
        <el-form-item label="区域">
          <el-select v-model="editingTask.patrolArea" placeholder="请选择">
            <el-option v-for="a in areaOptions" :key="a" :label="a" :value="a"/>
          </el-select>
        </el-form-item>
        <el-form-item label="路线">
          <el-input v-model="editingTask.patrolRoute"/>
        </el-form-item>
        <el-form-item label="频率">
          <el-input v-model="editingTask.patrolFrequency"/>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker v-model="editingTask.startTime" type="datetime" style="width:100%"/>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker v-model="editingTask.endTime" type="datetime" style="width:100%"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editingTask.status">
            <el-radio :label="'0'">未开始</el-radio>
            <el-radio :label="'1'">进行中</el-radio>
            <el-radio :label="'2'">已完成</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog=false">取消</el-button>
        <el-button type="primary" @click="saveTask">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.app-wrap { max-width:1200px; margin:20px auto; padding:16px; font-family: "Helvetica Neue", Arial, sans-serif; background:#f5f7fb; }
.mb-3 { margin-bottom:12px; }
.muted { color:#909399; }
.task-item { display:flex; justify-content:space-between; align-items:flex-start; padding:8px; margin-bottom:8px; border:1px solid #eee; cursor:pointer; border-radius:6px; }
.task-item:hover { background:#f8fafc; }
.status-0 { color:#f7b955; }
.status-1 { color:#67c23a; }
.status-2 { color:#909399; }
.photo { width:100%; height:100px; object-fit:cover; border-radius:4px; display:block; }

/* 保证地图有高度 */
.map-card { height: 320px; border:2px dashed #dcdfe6; }
#mapContainer { width: 100%; height: 100%; min-height: 300px; background: #f0f0f0; }
</style>
